package com.payment.ktb.activity.main1;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.payment.ktb.Interface.AlertInterface;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.activity.main4.BasicalInfoActivity;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsPay;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.model.BankCard;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.DeviceUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.Md5Utils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by syd on 2016/6/8.
 */
public class NocardOrderCreateActivity extends BaseActivity {


    String linkId = "";

    @BindView(R.id.tv_nocardordercreate_amount)
    TextView tv_nocardordercreate_amount;


    @BindView(R.id.tv_nocardordercreate_notes)
    TextView tv_nocardordercreate_notes;

    @BindView(R.id.ll_nocardordercreate_confrim_zhifubao)
    LinearLayout ll_nocardordercreate_confrim_zhifubao;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_nocardordercreate);
        ButterKnife.bind(this);
        if (ConstantsPay.orderType.equals(ConstantsPay.ORDERTYPET0)) {
            initTitle("快捷收款");
            tv_nocardordercreate_notes.setText(SharedPreferencesUtils.getString(ConstantsPay.T0Tip));
        } else if (ConstantsPay.orderType.equals(ConstantsPay.ORDERTYPET1)) {
            initTitle("普通收款");
            tv_nocardordercreate_notes.setText(SharedPreferencesUtils.getString(ConstantsPay.T1Tip));
            ll_nocardordercreate_confrim_zhifubao.setVisibility(View.GONE);
        } else {
            initTitle("收款");
        }

    }


    @OnClick({R.id.ll_nocardordercreate_confrim_wuka,R.id.ll_nocardordercreate_confrim_weixin,R.id.ll_nocardordercreate_confrim_zhifubao,R.id.btn_nocardordercreate_one,R.id.btn_nocardordercreate_two,
            R.id.btn_nocardordercreate_three,R.id.btn_nocardordercreate_four,R.id.btn_nocardordercreate_five,
            R.id.btn_nocardordercreate_six,R.id.btn_nocardordercreate_seven,R.id.btn_nocardordercreate_eight,
            R.id.btn_nocardordercreate_nine,R.id.btn_nocardordercreate_zero,R.id.btn_nocardordercreate_delete,
            R.id.btn_nocardordercreate_clean})
    public void clickEvent(View view) {

        switch (view.getId()) {

            //无卡支付
            case R.id.ll_nocardordercreate_confrim_wuka:
                if (checkAmount()) {
                    if (TextUtils.isEmpty(ConstantsPay.orderType)) {
                        submit(ConstantsPay.ORDERTYPET0,ConstantsPay.PAYTYPE1);
                    } else {
                        submit(ConstantsPay.orderType,ConstantsPay.PAYTYPE1);
                    }
                }
                break;

            //微信支付
            case R.id.ll_nocardordercreate_confrim_weixin:
                if (checkAmount()) {
                    if (TextUtils.isEmpty(ConstantsPay.orderType)) {
                        submit(ConstantsPay.ORDERTYPET0,ConstantsPay.PAYTYPE3);
                    } else {
                        submit(ConstantsPay.orderType,ConstantsPay.PAYTYPE3);
                    }
                }
                break;

            //支付宝支付
            case R.id.ll_nocardordercreate_confrim_zhifubao:
                if (checkAmount()) {
                    if (TextUtils.isEmpty(ConstantsPay.orderType)) {
                        submit(ConstantsPay.ORDERTYPET0,ConstantsPay.PAYTYPE4);
                    } else {
                        submit(ConstantsPay.orderType,ConstantsPay.PAYTYPE4);
                    }
                }
                break;



            //0
            case R.id.btn_nocardordercreate_zero:
                handleMoney("0");
                break;


            //1
            case R.id.btn_nocardordercreate_one:
                handleMoney("1");
                break;



            //2
            case R.id.btn_nocardordercreate_two:
                handleMoney("2");
                break;



            //3
            case R.id.btn_nocardordercreate_three:
                handleMoney("3");
                break;



            //4
            case R.id.btn_nocardordercreate_four:
                handleMoney("4");
                break;



            //5
            case R.id.btn_nocardordercreate_five:
                handleMoney("5");
                break;



            //6
            case R.id.btn_nocardordercreate_six:
                handleMoney("6");
                break;



            //7
            case R.id.btn_nocardordercreate_seven:
                handleMoney("7");
                break;



            //8
            case R.id.btn_nocardordercreate_eight:
                handleMoney("8");
                break;



            //9
            case R.id.btn_nocardordercreate_nine:
                handleMoney("9");
                break;



            //x
            case R.id.btn_nocardordercreate_delete:

                String temp = tv_nocardordercreate_amount.getText().toString().trim();
                if (!TextUtils.isEmpty(temp) && temp.length() > 0) {
                    tv_nocardordercreate_amount.setText(temp.substring(0,temp.length() - 1));
                }
                break;

            //清除
            case R.id.btn_nocardordercreate_clean:

                tv_nocardordercreate_amount.setText("");
                    break;




        }



    }


    /**
     *
     * @param amount
     */
    private void handleMoney(String amount) {

        String temp = tv_nocardordercreate_amount.getText().toString().trim();
         if(!TextUtils.isEmpty(temp) && temp.length() == 1 && temp.substring(0, 1).equals("0")){
            tv_nocardordercreate_amount.setText(amount);

         } else  {
             tv_nocardordercreate_amount.setText(temp + amount);

         }

    }


    /**
     *
     */
    private boolean checkAmount() {
        String temp = tv_nocardordercreate_amount.getText().toString().trim();
        if (TextUtils.isEmpty(temp)) {
            ToastUtils.showToast("请输入金额！");
            return false;
        }

//        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMin)) && Double.parseDouble(temp) < Double.parseDouble(SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMin))) {
//            ToastUtils.showToast("交易金额不能小于" + SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMin));
//            return false;
//        }
//        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMax))  && Double.parseDouble(temp) > Double.parseDouble(SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMax))) {
//            ToastUtils.showToast("交易金额不能大于" + SharedPreferencesUtils.getString(ConstantsPay.nocardOrderMax));
//            return false;
//        }

        return true;
    }


    /**
     *生成订单
     */
    private void submit(String typeOrder,String typePay) {


        progressDialogUtils.showProgress();

        //构造传输参数

        final String orderType = typeOrder;
        final String payType = typePay;
        final String amount = tv_nocardordercreate_amount.getText().toString().trim();
        String version = DeviceUtils.getVersionName();
        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        //
        String sign = Md5Utils.md5Hex(amount + linkId + orderType + payType + version + SharedPreferencesUtils.getString(ConstantsUser.userKey));

        //将参数放入map中
        final HashMap<String, String> map = new HashMap<String,String>();
        map.put("linkId",linkId);
        map.put("orderType",orderType);
        map.put("payType",payType);
        map.put("amount",amount);
        map.put("version",version);
        map.put("token",token);
        map.put("sign",sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.nocardOrderCreateState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {

                        ConstantsPay.amount = amount;
                        ConstantsPay.orderType = orderType;
                        ConstantsPay.orderNo = jsonObject.optString("orderNo");
                        ConstantsPay.orderTime = jsonObject.optString("orderTime");

                        if (jsonObject.optJSONArray("bindCards") != null && jsonObject.optJSONArray("bindCards").length() > 0) {

                            ConstantsPay.bindCards = new Gson().fromJson(jsonObject.optJSONArray("bindCards").toString(),new TypeToken<List<BankCard>>(){}.getType());
                        }

                        if (ConstantsPay.PAYTYPE1.equals(payType)) {
                            //无卡
                            startActivity(NocardOrderConfirmActivity.class);
                        } else if (ConstantsPay.PAYTYPE3.equals(payType)) {
                            //微信
                            Intent intent = new Intent(mContext,NocardOrderConfirmSaomaActivity.class);
                            intent.putExtra("codeImgUrl",jsonObject.optString("codeImgUrl"));
                            startActivity(intent);
                        } else if (ConstantsPay.PAYTYPE4.equals(payType)) {
                            //支付宝
                            Intent intent = new Intent(mContext,NocardOrderConfirmZhiFuBaoActivity.class);
                            intent.putExtra("codeImgUrl",jsonObject.optString("codeImgUrl"));
                            startActivity(intent);
                        }

                    } else if (Constants.ERR504_CODE.equals(code)) {

                        linkId = String.valueOf(new Date().getTime());
                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"), "取消", "去认证", new AlertInterface() {
                            @Override
                            public void confirm(Dialog alertDialog) {
                                getShopInfo();

                            }
                        });


                    } else if (Constants.ERR528_CODE.equals(code)) {


                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"), "取消", jsonObject.optString("buttonName"), new AlertInterface() {
                            @Override
                            public void confirm(Dialog alertDialog) {
                                activationAccount();

                            }
                        });
                        linkId = String.valueOf(new Date().getTime());

                    } else {
                        linkId = String.valueOf(new Date().getTime());
                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));

                    }
                } catch (JSONException e) {
                    linkId = String.valueOf(new Date().getTime());
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                linkId = String.valueOf(new Date().getTime());
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();

        linkId = String.valueOf(new Date().getTime());

    }





    /**
     * 商户信息查询
     * @return
     */
    public void getShopInfo() {


        progressDialogUtils.showProgress();

        //构造传输参数
        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        //MD5（picNbr+key）
        String sign = Md5Utils.md5Hex(SharedPreferencesUtils.getString(ConstantsUser.userKey));

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();
        map.put("token",token);
        map.put("sign",sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.shopInfoState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {

                        ConstantsUser.isEdit = jsonObject.optString("isEdit");
                        ConstantsUser.shopStatus = jsonObject.optString("shopStatus");
                        ConstantsUser.shopStatusCn  = jsonObject.optString("shopStatusCn");
                        ConstantsUser.selfStatus  = jsonObject.optString("selfStatus");
                        if (!TextUtils.isEmpty(jsonObject.optString("shopCert"))) {
                            SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPCERT,jsonObject.optString("shopCert"));
                        }
                        if (!TextUtils.isEmpty(jsonObject.optString("shopAccount"))) {
                            SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPACCOUNT,jsonObject.optString("shopAccount"));
                        }

                        if (!TextUtils.isEmpty(jsonObject.optString("shopBank"))) {
                            SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPBANK,jsonObject.optString("shopBank"));
                        }

                        if (!TextUtils.isEmpty(jsonObject.optString("pic1"))) {
                            SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1,jsonObject.optString("pic1"));
                        }

                        if (!TextUtils.isEmpty(jsonObject.optString("pic2"))) {
                            SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2,jsonObject.optString("pic2"));
                        }

                        if (!TextUtils.isEmpty(jsonObject.optString("pic3"))) {
                            SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC3,jsonObject.optString("pic3"));
                        }

                        if (!TextUtils.isEmpty(jsonObject.optString("pic4"))) {
                            SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC4,jsonObject.optString("pic4"));
                        }

                        ConstantsUser.picQr = jsonObject.optString("picQr");
                        ConstantsUser.showMsg = jsonObject.optString("showMsg");
                        ConstantsUser.orgId = jsonObject.optString("orgId");
                        ConstantsUser.activationStatus = jsonObject.optString("activationStatus");
                        startActivity(BasicalInfoActivity.class);

                    } else {

                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
            }
        });

    }





    /**
     *账号激活
     */
    private void activationAccount (){


        progressDialogUtils.showProgress();

        //构造传输参数

        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        //
        String sign = Md5Utils.md5Hex(linkId + SharedPreferencesUtils.getString(ConstantsUser.userKey));

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();
        map.put("linkId",linkId);
        map.put("token",token);
        map.put("sign",sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.shopActivationSmsState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {

                        ConstantsPay.amount = "1";
                        ConstantsPay.orderType = ConstantsPay.ORDERTYPET1;
                        ConstantsPay.orderNo = jsonObject.optString("orderNo");
                        ConstantsPay.bankNo = jsonObject.optString("bankNo");
                        ConstantsPay.cardPhone = jsonObject.optString("cardPhone");
                        ConstantsPay.shopCert = jsonObject.optString("shopCert");
                        ConstantsPay.shopAccount = jsonObject.optString("shopAccount");
                        Intent intent = new Intent(mContext,AddBankcardActivity.class);
                        intent.putExtra("fromPersionalInfo","fromPersionalInfo");
                        startActivity(intent);

                    } else if (Constants.ERR504_CODE.equals(code)) {


                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"), "取消", "去认证", new AlertInterface() {
                            @Override
                            public void confirm(Dialog alertDialog) {
                                startActivity(BasicalInfoActivity.class);
                            }
                        });


                    } else {

                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
            }
        });

    }




}
